/*
 * Copyright (c) 2020 Carnegie Lee
 * All rights reserved
 */
package com.geekc.zkdistributelock.lock.impl;

import com.geekc.zkdistributelock.constant.DistributeLockConst;
import com.geekc.zkdistributelock.lock.DistributeLock;
import com.geekc.zkdistributelock.lock.DistributeLockFactory;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 分布式锁工厂类
 * @author Carnegie Lee
 */
@Component
public class DefaultDistributeLockFactory implements DistributeLockFactory, ApplicationContextAware {

    private CuratorFramework curatorFramework;

    @Override
    public DistributeLock createDefaultLock(String lockName) {
        DistributeLock distributeLock = new DefaultDistributeLock(curatorFramework, lockName);
        return distributeLock;
    }

    @Override
    public DistributeLock createOptimizeLock(String lockName) {
        DistributeLock distributeLock = new OptimizeDistributeLock(curatorFramework, lockName);
        return distributeLock;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.curatorFramework = (CuratorFramework) applicationContext.getBean("curatorFramework");
        try {
            if (null == this.curatorFramework.checkExists().forPath(DistributeLockConst.DISTRIBUTE_LOCK_ROOT_PATH)) {
                this.curatorFramework.create()
                        .creatingParentsIfNeeded()
                        .withMode(CreateMode.PERSISTENT)
                        .forPath(DistributeLockConst.DISTRIBUTE_LOCK_ROOT_PATH);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
